import { createElement, useEffect, useState, useRef } from 'rax';
import { getSearchParams } from 'rax-app';
import View from 'rax-view';
import Image from 'rax-image';
import Text from 'rax-text';
import {
  postMaxImgDownLoad,
  queryUserImgDEL,
  queryTaskById,
} from '@/api';
import { actionSheet } from '@uni/apis';
import NavBar from '@/components/NavBar';
import './index.css';

let timer = null;
const MyportrayDetail = () => {
  const [titleBarHeight, setTitleBarHeight] = useState(0);
  const [img, setImg] = useState('');
  const [use_num, setUseNum] = useState('');
  const [tmpl_name, setTmplName] = useState('');
  const [id, setId] = useState(null);
  const [showDelete, setShowDelete] = useState(false);
  const siv = useRef(null);
  const [flag, setFlag] = useState(true);
  const [taskId, setTaskId] = useState(null);

  useEffect(() => {
    my.getSystemInfo({
      success: (res) => {
        let height = res.titleBarHeight + res.statusBarHeight
        setTitleBarHeight(height)
      }
    });
    const params = getSearchParams()
    // let params = router.params;
    let {
      img,
      tmpl_name,
      use_num,
      id
    } = params;
    setId(id)
    setImg(img);
    setUseNum(use_num);
    setTmplName(tmpl_name);
    return () => {
      clearInterval(siv.current);
    };
  }, []);

  const onChooseTemplate = () => {
    const params = getSearchParams()
    let {
      tmpl_name,
      tmpl_id,
      tmpl_img,
      tmpl_tmb_img,
      use_num,
      backdrop_img,
      number
    } = params;
    let app = getApp();
    app.globalData.templateInfo = {
      tmpl_name,
      tmpl_id,
      tmpl_img,
      tmpl_tmb_img,
      use_num,
      backdrop_img,
      number
    }
    my.switchTab({
      url: `/pages/index/index?tmpl_name=${tmpl_name}&tmpl_tmb_img=${tmpl_tmb_img}&tmpl_img=${tmpl_img}&tmpl_id=${tmpl_id}&use_num=${use_num}&number=${number}&backdrop_img=${backdrop_img}`,
    })
    // my.navigateTo({
    //   url: `/pages/index/index?tmpl_name=${tmpl_name}&tmpl_tmb_img=${tmpl_tmb_img}&tmpl_img=${tmpl_img}&tmpl_id=${tmpl_id}&use_num=${use_num}&number=${number}&backdrop_img=${backdrop_img}`
    // })
  }

  const hdDownload = () => {
    if (flag) {
      setFlag(false);
      postMaxImgDownLoad({img_url: img})
        .then(res=>{
          my.showLoading({
            content: '加载中',
          });
          if (res.url) {
            my.downloadFile({
              url: res.url,
              success: (response) => {
                let filePath = response.apFilePath;
                my.saveImage({
                  url: filePath,
                  success: () => {
                    my.alert({
                      title: '保存成功',
                    });
                    my.hideLoading();
                    setFlag(true);
                  },
                });
              },
              fail: (err) => {
                my.showModal({
                  content: err.errMsg,
                  type: 'none'
                });
                setFlag(true);
              },
            });
          }
          else {
            setTaskId(res.TaskId);
          }
        })
    }
  }

  useEffect(()=>{
    siv.current = setInterval(()=>{
      onLoadData();
    }, 2000)
    return () => clearInterval(siv.current);
  }, [taskId]);

  const onLoadData = () => {
    queryTaskById({task_id: taskId})
      .then(data=>{
        if (data.Status == "Success") {
          siv.current = null;
          clearInterval(siv.current);
          my.downloadFile({
            url: data.Result.data.url,
            header: {
              "content-type": "application/json",
            },
            success: (response) => {
              let filePath = response.apFilePath;
              my.saveImage({
                url: filePath,
                success: () => {
                  my.alert({
                    title: '保存成功',
                  });
                  my.hideLoading();
                  setFlag(true);
                },
              });
            },
            fail: (err) => {
              my.showModal({
                content: err.errMsg,
                type: 'none'
              });
              setFlag(true);
            }
          });
          return;
        }
      });
  }

  const onDownload = () => {
    my.downloadFile({
      url: img,
      success: (res) => {
        let filePath = res.apFilePath;
        my.saveImage({
          url: filePath,
          success: () => {
            my.alert({
              title: '保存成功',
            });
          },
        });
      },
      fail: (err) => {
        my.showModal({
          content: err.errMsg,
          type: 'none'
        });
      },
    });
  }

  const onRemove = () => {
    setShowDelete(true);
    // actionSheet({
    //   itemList: ['删除']
    // }).then(res => {
    //   let {
    //     tapIndex
    //   } = res;
    //   if (tapIndex == 0) {
    //     queryUserImgDEL({id: id})
    //       .then(res=>{
    //         my.showToast({
    //           content: '删除成功',
    //           type: 'none',
    //           zIndex: 9999,
    //           success: () => {
    //             my.navigateBack();
    //           }
    //         });
    //       })
    //   }
    // });
  }

  const onSureDelete = () => {
    queryUserImgDEL({id: id})
      .then(res=>{
        my.showToast({
          content: '删除成功',
          type: 'none',
          zIndex: 9999,
          success: () => {
            my.navigateBack();
          }
        });
      })
  }

  return (
    <View className='myportray_main'>
      {/* <NavBar
        title="我的写真"
        onClick={()=>{doBack()}}
      /> */}
      <View
        className='myportray_section'
        style={{
          paddingTop: `${titleBarHeight}px`
        }}
      >
        <View
          style={{
            height: `calc(100vh - ${titleBarHeight}px)`
          }}
          className='myportray_content'
        >
          <View className='myportray_content_scetion'>
            <View className='myportray_content_main'>
              <View className='myportray_content_block'>
                <Image
                  source={{
                    uri: img
                  }}
                  mode='aspectFill'
                  className='myportray_content_block_img'
                />
                <View className='myportray_content_block_info'>
                  <View className='myportray_content_block_info_label'>
                    <Image
                      source={{
                        uri: 'https://jala-test-images.sndaurl.cn/images/makeup.png'
                      }}
                      mode='aspectFill'
                      className='myportray_content_block_info_label_icon'
                    />
                    {tmpl_name}
                  </View>
                  已有{use_num}人使用
                </View>
              </View>
              <View className='myportray_content_block remote'>
                <Image
                   source={{
                    uri: img
                  }}
                  mode='aspectFill'
                  className='myportray_content_block_img'
                />
                <View className='myportray_content_block_info'>
                  <View className='myportray_content_block_info_label'>
                    <Image
                      source={{
                        uri: 'https://jala-test-images.sndaurl.cn/images/makeup.png'
                      }}
                      mode='aspectFill'
                      className='myportray_content_block_info_label_icon'
                    />
                    {tmpl_name}
                  </View>
                  已有{use_num}人使用
                </View>
              </View>
            </View>
            <View
              className='myportray_content_actions'
              onClick={()=>{
                onChooseTemplate()
              }}
            >
              <View className='myportray_content_action'>使用模版再次变妆</View>
            </View>
          </View>
          <View className='myportray_footer'>
            <View className='myportray_footer_tip'>
              <View className='myportray_footer_tip_value'>
              点击分享您的美
              </View>
            </View>
            <View className='myportray_footer_action'>
              <View className='myportray_footer_action_item' onClick={()=>{hdDownload()}}>
                <Image
                  source={{
                    uri: 'https://jala-test-images.sndaurl.cn/images/actions/HdDownloda.png'
                  }}
                  mode='aspectFill'
                  className='myportray_footer_action_item_icon'
                />
                <View className='myportray_footer_action_item_text'>高清下载</View>
              </View>
              <View className='myportray_footer_action_item' onClick={()=>{onDownload()}}>
                <Image
                  source={{
                    uri: 'https://jala-test-images.sndaurl.cn/images/actions/download.png'
                  }}
                  mode='aspectFill'
                  className='myportray_footer_action_item_icon'
                />
                <View className='myportray_footer_action_item_text'>下载</View>
              </View>
              <button
                open-type="share"
                className='myportray_footer_action_item'
                onClick={()=>{
                  my.showSharePanel();
                }}
              >
                <Image
                  source={{
                    uri: 'https://jala-test-images.sndaurl.cn/images/actions/share_icon.png'
                  }}
                  mode='aspectFill'
                  className='myportray_footer_action_item_icon'
                />
                <View className='myportray_footer_action_item_text'>分享</View>
              </button>
              <View className='myportray_footer_action_item' onClick={()=>{onRemove()}}>
                <Image
                  source={{
                    uri: 'https://jala-test-images.sndaurl.cn/images/actions/delete.png'
                  }}
                  mode='aspectFill'
                  className='myportray_footer_action_item_icon'
                />
                <View className='myportray_footer_action_item_text'>删除</View>
              </View>
            </View>
          </View>
        </View>
      </View>
      {
        showDelete ? (
          <View className='mask' onClick={()=>{setShowDelete(false)}}>
            <View className='delete_view'>
              <View className='delete_view_sure' onClick={()=>{onSureDelete()}}>删除</View>
              <View className='delete_view_cancel' onClick={()=>{setShowDelete(false)}}>取消</View>
            </View>
          </View>
        ) : null
      }
    </View>
  )
}
export default MyportrayDetail;
